<template>
  <div class="product">
    <!-- 创建一级分类 -->
    <div class="product_one">
      <el-form
        :model="numberValidateForm"
        ref="numberValidateForm"
        label-width="100px"
        class="one-ruleForm"
      >
        <el-form-item
          label="一级分类"
          prop="typeOne"
          :rules="[{ required: true, message: '分类不能为空' }]"
        >
          <el-input
            type="typeOne"
            v-model="numberValidateForm.typeOne"
            placeholder="请输入产品的类别"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 添加图片 -->
        <el-form-item label="分类图片:" prop="img">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            accept="image/jpg,image/png,image/jpeg"
            :on-change="imgBroadcastChange"
            :auto-upload="false"
          >
            <img
              v-if="numberValidateForm.Img"
              :src="numberValidateForm.Img"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('numberValidateForm')"
            >添加</el-button
          >
          <el-button :loading="loading" @click="resetForm('numberValidateForm')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 一级分类列表 -->
    <div class="product_list">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="500"
        class="table-one"
      >
        <el-table-column label="id">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row._id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类别名称">
          <template slot-scope="scope">
            <p>{{ scope.row.typeOne }}</p>
          </template>
        </el-table-column>
        <el-table-column label="Logo">
          <template slot-scope="scope">
            <p><img :src="scope.row.Img" alt="" height="40" /></p>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 编辑 -->
    <el-dialog
      title="修改一级列表信息"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        :model="typeOne"
        ref="typeOne"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="分类"
          prop="typeOne"
          :rules="[{ required: true, message: '分类不能为空' }]"
        >
          <el-input
            type="typeOne"
            v-model="typeOne.typeOne"
            placeholder="请输入品牌 如 小米、华为"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 添加图片 -->
        <el-form-item label="分类图片:" prop="img">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            accept="image/jpg,image/png,image/jpeg"
            :on-change="imgBroadcastChange1"
            :auto-upload="false"
          >
            <img v-if="typeOne.Img" :src="typeOne.Img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpd('typeOne')"
          >确 定</el-button
        >
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getProduct, addProduct, delProduct, xiuProduct } from "@/api/product";
export default {
  data() {
    return {
      // 一类
      numberValidateForm: {
        typeOne: "",
        Img: "",
      },
      loading: false,
      tableData: [],
      typeOne: {
        typeOne: "",
        Img: "",
        _id: "",
      },
      //弹出层状态
      dialogVisible: false,
    };
  },
  created() {
    this.render();
  },
  methods: {
    render() {
      //获取一级分类列表
      getProduct().then((res) => {
        this.tableData = res;
      });
    },
    // 添加一级分类
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          addProduct(this.numberValidateForm).then(() => {
            this.loading = false;
            this.$message("添加成功");
            //添加成功并重新渲染
            this.$refs[formName].resetFields();
            this.render();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    imgBroadcastChange(file, fileList) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (isLt1M) {
        // uploadImgToBase64()返回一个Promise对象，通过.then()获取其数据。其中data.result是图片转成的base64值
        this.uploadImgToBase64(file.raw).then((data) => {
          this.numberValidateForm.Img = data.result;
        });
      } else {
        this.$message.error("上传封面图片大小不能超过 1MB!");
      }
    },
    imgBroadcastChange1(file, fileList) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (isLt1M) {
        // uploadImgToBase64()返回一个Promise对象，通过.then()获取其数据。其中data.result是图片转成的base64值
        this.uploadImgToBase64(file.raw).then((data) => {
          this.typeOne.Img = data.result;
        });
      } else {
        this.$message.error("上传封面图片大小不能超过 1MB!");
      }
    },
    //将上传的图片转换成Base64
    uploadImgToBase64(file) {
      //核心方法，将图片转成base64字符串形式
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
          // 图片转base64完成后返回reader对象
          resolve(reader);
        };
        reader.onerror = reject;
      });
    },

    //编辑赋值给弹出层
    handleEdit(index, row) {
      console.log(row);
      this.dialogVisible = true;
      this.typeOne.typeOne = row.typeOne;
      this.typeOne.Img = row.Img;
      this.typeOne._id = row._id;
    },
    //确认修改
    handleUpd(formName) {
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.typeOne;
          xiuProduct(data).then(() => {
            this.$message(`修改成功`);
            _this.dialogVisible = false;
            //  修改成功，初始化列表
            _this.render();
          });
        }
      });
    },
    //删除一级分类
    handleDelete(index,row) {
      this.$confirm("为了不影响产生不必要的影响，请确认后再删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delProduct(row).then(() => {
            this.$message("删除成功");
            this.render();
          });
        })
        .catch(() => {
          this.$message("取消成功");
        });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
.product {
  margin: 50px auto;
  width: 80%;
  text-align: center;
}
.one-ruleForm {
  display: flex;
  justify-content: space-between;
}
.product_list {
  margin-left: 2%;
  width: 100%;
  border: 1px solid #cdcdcd;
}
.el-table td,
.el-table th {
  text-align: center !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>